package org.example.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @description: redis6序列化配置 (借助Jackson对redis的value进行json序列号化)
 * @author: 谢超
 * @date: 2023/07/23 11:33
 **/
@Configuration
public class RedisTemplateConfiguration {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 配置序列化规则
        // 创建一个json的序列化对象
        Jackson2JsonRedisSerializer jackson2Redis = new Jackson2JsonRedisSerializer(Object.class);

        // 序列化容器
        // ObjectMapper类(com.fasterxml.jackson.databind.ObjectMapper)是Jackson的主要类，它可以帮助我们快速的进行各个类型和Json类型的相互转换
        ObjectMapper objectMapper = new ObjectMapper();
        // 任何属性可见
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        // 将JSON转化为对象，不设置会转化成Map类型
        // objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL)

        jackson2Redis.setObjectMapper(objectMapper);

        // 设置key-value序列化规则
        // 设置key序列化方式String
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 设置value的序列化方式为json
        redisTemplate.setValueSerializer(jackson2Redis);

        // 设置hash-value序列化规则
        // 设置key序列化方式String
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // 设置value的序列化方式为json
        redisTemplate.setHashValueSerializer(jackson2Redis);

        return redisTemplate;
    }

}
